package com.gamatechno.solodestination;

import hirondelle.date4j.DateTime;

import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.gamatechno.adapter.CustomAdapter;
import com.gamatechno.solodestination.model.DBHandler;
import com.gamatechno.solodestination.model.Event;
import com.gamatechno.solodestination.model.ServiceHandler;
import com.roomorama.caldroid.CaldroidFragment;
import com.roomorama.caldroid.CaldroidListener;
import com.gamatechno.animation.SlidingUpPanelLayout;
import com.gamatechno.animation.SlidingUpPanelLayout.PanelSlideListener;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

public class EventActivity extends FragmentActivity {
	private boolean undo = false;
	private CaldroidFragment caldroidFragment;
	private CaldroidFragment dialogCaldroidFragment;
	private ProgressDialog pDialog;
	private String url = "http://sms.gamatechno.com/solo_destination/services/getEvent.php?method=allevent&format=json";
	List<Event> dataList;
	private static final String TAG_ID = "id";
	private static final String TAG_NAME = "name";
	private static final String TAG_DESC = "description";
	private static final String TAG_LAT = "lat";
	private static final String TAG_LON = "lng";
	private static final String TAG_STARTDATE = "startDate";
	private static final String TAG_IMAGES = "images";
	private static final String TAG_ENDDATE = "endDate";
	private static final String TAG_CATEGORY = "category";
	ListAdapter adapter;
	ListView eList;
	TextView eText;
	LinearLayout slideHandleButton;
	DBHandler db = new DBHandler(this);
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

	private void setCustomResourceForDates(String date) {

		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		Date myDate = null;

		try {
			if (caldroidFragment != null) {
				myDate = dateFormat.parse(date);
				caldroidFragment.setBackgroundResourceForDate(R.color.red,
						myDate);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy");
		setContentView(R.layout.activity_event);
		eText = (TextView) findViewById(R.id.noevent);
		eList = (ListView) findViewById(R.id.eventlist);
		new GetEvent().execute();
		// fvcking actionbar//
		Bitmap b = BitmapFactory.decodeResource(getResources(),
				R.drawable.header_img);
		BitmapDrawable bd = new BitmapDrawable(getResources(), b);
		ActionBar ab = getActionBar();
		ab.setBackgroundDrawable(bd);
		LayoutInflater inflater = (LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View v = inflater.inflate(R.layout.actionbar_logo, null);
		ab.setCustomView(v);
		ab.setDisplayShowCustomEnabled(true);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setLogo(R.drawable.ic_home);
		getActionBar().setTitle("");
		String Today = formatter.format(new Date());
		if (db.cekDateHasEvent(Today)) {
			showEventLis(Today);
		} else {
			eText.setVisibility(View.VISIBLE);
			eList.setVisibility(View.GONE);
		}
		final SlidingUpPanelLayout layout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
		layout.setShadowDrawable(getResources().getDrawable(
				R.drawable.above_shadow));
		layout.setAnchorPoint(0.3f);
		layout.setEnableDragViewTouchEvents(true);

		layout.setPanelSlideListener(new PanelSlideListener() {

			@Override
			public void onPanelSlide(View panel, float slideOffset) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onPanelExpanded(View panel) {
				// TODO Auto-generated method stub
		
			}

			@Override
			public void onPanelCollapsed(View panel) {
				// TODO Auto-generated method stub
			

			}

			@Override
			public void onPanelAnchored(View panel) {
				// TODO Auto-generated method stub
			}
		});

		// Setup caldroid fragment
		// **** If you want normal CaldroidFragment, use below line ****
		caldroidFragment = new CaldroidFragment();

		// //////////////////////////////////////////////////////////////////////
		// **** This is to show customized fragment. If you want customized
		// version, uncomment below line ****
		// caldroidFragment = new CaldroidSampleCustomFragment();

		// Setup arguments

		// If Activity is created after rotation
		if (savedInstanceState != null) {
			caldroidFragment.restoreStatesFromKey(savedInstanceState,
					"CALDROID_SAVED_STATE");
		}
		// If activity is created from fresh
		else {
			Bundle args = new Bundle();
			Calendar cal = Calendar.getInstance();
			args.putInt(CaldroidFragment.MONTH, cal.get(Calendar.MONTH) + 1);
			args.putInt(CaldroidFragment.YEAR, cal.get(Calendar.YEAR));
			args.putBoolean(CaldroidFragment.ENABLE_SWIPE, true);
			args.putBoolean(CaldroidFragment.SIX_WEEKS_IN_CALENDAR, true);

			// Uncomment this to customize startDayOfWeek
			// args.putInt(CaldroidFragment.START_DAY_OF_WEEK,
			// CaldroidFragment.TUESDAY); // Tuesday
			caldroidFragment.setArguments(args);
		}

		// Attach to the activity
		FragmentTransaction t = getSupportFragmentManager().beginTransaction();
		t.replace(R.id.calendar1, caldroidFragment);
		t.commit();

		// Setup listener
		final CaldroidListener listener = new CaldroidListener() {

			@Override
			public void onSelectDate(Date date, View view) {
				Toast.makeText(getApplicationContext(), formatter.format(date),
						Toast.LENGTH_SHORT).show();

				String sDate = dateFormat.format(date);
				Log.d("sdate", "-->" + sDate);
				if (db.cekDateHasEvent(sDate)) {
					showEventLis(sDate);
				} else {
					eText.setVisibility(View.VISIBLE);
					eList.setVisibility(View.GONE);
				}

			}

			@Override
			public void onChangeMonth(int month, int year) {
				String text = "month: " + month + " year: " + year;
				// Toast.makeText(getApplicationContext(), text,
				// Toast.LENGTH_SHORT).show();
				eText.setVisibility(View.VISIBLE);
				eList.setVisibility(View.GONE);
			}

			@Override
			public void onLongClickDate(Date date, View view) {
				// Toast.makeText(getApplicationContext(),
				// "Long click " + formatter.format(date),
				// Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onCaldroidViewCreated() {
				if (caldroidFragment.getLeftArrowButton() != null) {
					// Toast.makeText(getApplicationContext(),
					// "Caldroid view is created", Toast.LENGTH_SHORT)
					// .show();
				}
			}

		};

		eList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				TextView tID = (TextView) v.findViewById(R.id.ID);
				String id = tID.getText().toString();
				Log.d("id selected", id);
				Intent i = new Intent(EventActivity.this,
						EventDetailActivity.class);
				i.putExtra("id", id);
				startActivity(i);

			}
		});

		// Setup Caldroid
		caldroidFragment.setCaldroidListener(listener);

		final TextView textView = (TextView) findViewById(R.id.textview);

		final Button customizeButton = (Button) findViewById(R.id.customize_button);
		// HIDE BUTTON
		customizeButton.setVisibility(View.GONE);

		// Customize the calendar
		customizeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (undo) {
					customizeButton.setText(getString(R.string.customize));
					textView.setText("");

					// Reset calendar
					caldroidFragment.clearDisableDates();
					caldroidFragment.clearSelectedDates();
					caldroidFragment.setMinDate(null);
					caldroidFragment.setMaxDate(null);
					caldroidFragment.setShowNavigationArrows(true);
					caldroidFragment.setEnableSwipe(true);
					caldroidFragment.refreshView();
					undo = false;
					return;
				}

				// Else
				undo = true;
				customizeButton.setText(getString(R.string.undo));
				Calendar cal = Calendar.getInstance();

				// Min date is last 7 days
				cal.add(Calendar.DATE, -7);
				Date minDate = cal.getTime();

				// Max date is next 7 days
				cal = Calendar.getInstance();
				cal.add(Calendar.DATE, 14);
				Date maxDate = cal.getTime();

				// Set selected dates
				// From Date
				cal = Calendar.getInstance();
				cal.add(Calendar.DATE, 2);
				Date fromDate = cal.getTime();

				// To Date
				cal = Calendar.getInstance();
				cal.add(Calendar.DATE, 3);
				Date toDate = cal.getTime();

				// Set disabled dates
				ArrayList<Date> disabledDates = new ArrayList<Date>();
				for (int i = 5; i < 8; i++) {
					cal = Calendar.getInstance();
					cal.add(Calendar.DATE, i);
					disabledDates.add(cal.getTime());
				}

				// Customize
				caldroidFragment.setMinDate(minDate);
				caldroidFragment.setMaxDate(maxDate);
				caldroidFragment.setDisableDates(disabledDates);
				caldroidFragment.setSelectedDates(fromDate, toDate);
				caldroidFragment.setShowNavigationArrows(false);
				caldroidFragment.setEnableSwipe(false);

				caldroidFragment.refreshView();

				// Move to date
				// cal = Calendar.getInstance();
				// cal.add(Calendar.MONTH, 12);
				// caldroidFragment.moveToDate(cal.getTime());

				String text = "Today: " + formatter.format(new Date()) + "\n";
				text += "Min Date: " + formatter.format(minDate) + "\n";
				text += "Max Date: " + formatter.format(maxDate) + "\n";
				text += "Select From Date: " + formatter.format(fromDate)
						+ "\n";
				text += "Select To Date: " + formatter.format(toDate) + "\n";
				for (Date date : disabledDates) {
					text += "Disabled Date: " + formatter.format(date) + "\n";
				}

				textView.setText(text);
			}
		});

		Button showDialogButton = (Button) findViewById(R.id.show_dialog_button);
		// HIDEBUTTON//
		showDialogButton.setVisibility(View.GONE);
		final Bundle state = savedInstanceState;
		showDialogButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// Setup caldroid to use as dialog
				dialogCaldroidFragment = new CaldroidFragment();
				dialogCaldroidFragment.setCaldroidListener(listener);

				// If activity is recovered from rotation
				final String dialogTag = "CALDROID_DIALOG_FRAGMENT";
				if (state != null) {
					dialogCaldroidFragment.restoreDialogStatesFromKey(
							getSupportFragmentManager(), state,
							"DIALOG_CALDROID_SAVED_STATE", dialogTag);
					Bundle args = dialogCaldroidFragment.getArguments();
					if (args == null) {
						args = new Bundle();
						dialogCaldroidFragment.setArguments(args);
					}
					args.putString(CaldroidFragment.DIALOG_TITLE,
							"Select a date");
				} else {
					// Setup arguments
					Bundle bundle = new Bundle();
					// Setup dialogTitle
					bundle.putString(CaldroidFragment.DIALOG_TITLE,
							"Select a date");
					dialogCaldroidFragment.setArguments(bundle);
				}

				dialogCaldroidFragment.show(getSupportFragmentManager(),
						dialogTag);
			}
		});
	}

	/**
	 * Save current states of the Caldroid here
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);

		if (caldroidFragment != null) {
			caldroidFragment.saveStatesToKey(outState, "CALDROID_SAVED_STATE");
		}

		if (dialogCaldroidFragment != null) {
			dialogCaldroidFragment.saveStatesToKey(outState,
					"DIALOG_CALDROID_SAVED_STATE");
		}
	}

	// SEARCH ICON AND CLICKABLE
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);

		// Associate searchable configuration with the SearchView
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// toggle nav drawer on selecting action bar app icon/title
		// Handle action bar actions click
		switch (item.getItemId()) {
		case R.id.action_search:
			return true;
		case android.R.id.home:
			this.finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/* *
	 * Called when invalidateOptionsMenu() is triggered
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// if nav drawer is opened, hide the action items
		SearchView mSearch = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();
		int searchimg = getResources().getIdentifier(
				"android:id/search_button", null, null);
		ImageView v = (ImageView) mSearch.findViewById(searchimg);
		v.setImageResource(R.drawable.ic_action_search);
		// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
		menu.findItem(R.id.action_search).setVisible(true);
		return super.onPrepareOptionsMenu(menu);
	}

	private class GetEvent extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pDialog = new ProgressDialog(EventActivity.this);
			pDialog.setMessage("Please Wait...");
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ServiceHandler sh = new ServiceHandler();
			String JsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
			JSONArray result;
			if (JsonStr != null) {
				try {
					JSONObject jsonO = new JSONObject(JsonStr);
					result = jsonO.getJSONArray("result");
					Log.d("result", "-->" + result);
					for (int i = 0; i < result.length(); i++) {
						JSONObject j = result.getJSONObject(i);
						Event e = new Event();
						e.setId(Integer.parseInt(j.getString(TAG_ID)));
						e.setName(j.getString(TAG_NAME));
						e.setDescription(j.getString(TAG_DESC));
						e.setLat(j.getString(TAG_LAT));
						e.setLon(j.getString(TAG_LON));
						e.setStartDate(j.getString(TAG_STARTDATE));
						e.setEndDate(j.getString(TAG_ENDDATE));
						e.setImages(j.getString(TAG_IMAGES));
						e.setCategory(j.getString(TAG_CATEGORY));
						db.addEvent(e);
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (pDialog.isShowing())
				pDialog.dismiss();

			dataList = db.getEventList();

			for (Event e : dataList) {
				setCustomResourceForDates(e.getStartDate());
			}
			caldroidFragment.refreshView();

		}

	}

	private void showEventLis(String Date) {
		eText.setVisibility(View.GONE);
		eList.setVisibility(View.VISIBLE);
		ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
		dataList = db.getEventListByDate(Date);

		for (Event e : dataList) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("ID", String.valueOf(e.getId()));
			map.put(TAG_STARTDATE, e.getStartDate());
			setCustomResourceForDates(e.getStartDate());
			map.put(TAG_NAME, e.getName());
			list.add(map);
		}

		adapter = new CustomAdapter(getApplicationContext(), list,
				R.layout.list_item_event, new String[] { "ID", TAG_STARTDATE,
						TAG_NAME },
				new int[] { R.id.ID, R.id.eTgl, R.id.eEvent });

		eList.setAdapter(adapter);

	}

}
